package com.zyf.service.video;

import cn.hutool.core.io.FileUtil;
import com.zyf.service.audio.HandleAudioService;
import com.zyf.service.MergeDataService;
import com.zyf.utils.PublicEnums;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 短视频制作处理类
 */
public class MakeVideoService {

    private static final double RATE = 0.002;

    /**
     * 一键合成视频
     * @return
     * @throws Exception
     */
    public boolean makeVideo(String audiopath,String backpath,String imageFolder) throws Exception {
        try {
            //校验字幕源文件是否格式正确
            Map<String, String> resMap =  new HandleAudioService().mergeAudioAndBackBySrt(audiopath, backpath);
            String message = MergeDataService.makeShortvedioByImages(imageFolder, resMap.get("audio"), PublicEnums.MergeVedioType.SingleImg.getValue());//批量合成视频
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return true;
    }

    /**
     * 读取源文件
     */
    private List<String> checkSrcTxtByLine(String filepath) throws FileNotFoundException {
        List<String> messages=new ArrayList<>();
        InputStream inputstream = new FileInputStream(new File(filepath));
        BufferedReader reader = null;
        String temp = "";
        List<String> newSrtList = new ArrayList<>();
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            while ((temp = reader.readLine()) != null) {

            }
        } catch (IOException e) {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return messages;
    }

    /**
     * 一键合成文字书签视频
     * @return
     * @throws Exception
     */
    public boolean makeVideoByTag(String audiopath,String backpath,String imageFolder) throws Exception {
        try {
            List<File> srctxtList = FileUtil.loopFiles(new File(audiopath).getParent(), file -> file.isFile() && file.getName().endsWith(".txt"));
            //合成音频
            Map<String, String> resMap =  new HandleAudioService().mergeAudioAndBackBySrtAndTag(audiopath, backpath);
            //合成视频字幕  resMap.get("audio")
            String message = MergeDataService.makeShortvedioByImagesByTag(imageFolder,  resMap.get("audio"),srctxtList.get(0).getAbsolutePath());//合成视频
        } catch (Exception e) {
            throw new RuntimeException( e.getMessage());
        }
        return true;
    }




}
